from forms_builder.forms.models import FormEntry, FieldEntry 
from django.shortcuts import render_to_response
from forms_builder.forms.forms import FormForForm
from django.template import RequestContext

from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger 

def book_index(request):
	'''book index and search engine'''
	try:
		kword = request.GET['w']
		mbooks = FieldEntry.objects.filter(field_id=1, value__icontains=kword)
	except KeyError:
		mbooks = FieldEntry.objects.filter(field_id=1)

	pag = Paginator(mbooks, 13)

	try:
		p = int(request.GET.get('p', '1'))
	except ValueError:
		p = 1

	try:
		books = pag.page(p)
	except (EmptyPage, InvalidPage):
		books = pag.page(pag.num_pages)

	template = 'bform/book_index.html'
	context = {
		'books': books,
	}

	return render_to_response(template, context, RequestContext(request))

def book_list(request):
	 '''show a book list'''
	 book_titles = FieldEntry.objects.filter(field_id=1)

	 template = 'bform/book_list.html'
	 context = {
		  'book_list': book_titles,
	 }

	 return render_to_response(template, context)

def book_detail(request, entry_id):
	'''show book info. in details'''
	cform = FieldEntry.objects.filter(entry=entry_id)[0].entry.form
	labels = [f.label for f in FormForForm(cform)]
	values = [f.value for f in FieldEntry.objects.filter(entry=entry_id)]
	kvs = zip(labels, values)

	template = 'bform/book_detail.html'
	context = { 'key_values': kvs }

	return render_to_response(template, context, RequestContext(request))
